package com.lam.dormitory.common.quartz;

import com.lam.dormitory.entity.Quartz;
import com.lam.dormitory.util.ResponseTemplate;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Job 工具类
 */
@Component
public class JobUtil {
    @Autowired
    @Qualifier("scheduler")
    private Scheduler scheduler;

    /**
     * 新建一个任务
     *
     */
    public ResponseTemplate addJob(Quartz quartz) throws Exception  {

//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date=df.parse(quartz.getStartTime());
//        Date date = new Date();
//        quartz.setStartTime(date);
        if (!CronExpression.isValidExpression(quartz.getCronExpression())) {
            return new ResponseTemplate(500,"Illegal cron expression"); //表达式格式不正确
        }

        JobDetail jobDetail=null;
        //构建job信息
        if("JobOne".equals(quartz.getJobGroup())) {
            jobDetail = JobBuilder.newJob(JobOne.class).withIdentity(quartz.getJobName(), quartz.getJobGroup()).build();
        }
        if("JobTwo".equals(quartz.getJobGroup())) {
            jobDetail = JobBuilder.newJob(JobTwo.class).withIdentity(quartz.getJobName(), quartz.getJobGroup()).build();
        }

        //表达式调度构建器(即任务执行的时间,不立即执行)
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression()).withMisfireHandlingInstructionDoNothing();

        //按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(quartz.getJobName(), quartz.getJobGroup()).startAt(new Date())
                .withSchedule(scheduleBuilder).build();

        //传递参数
        if(quartz.getInvokeParam()!=null && !"".equals(quartz.getInvokeParam())) {
            trigger.getJobDataMap().put("invokeParam",quartz.getInvokeParam());
        }
        scheduler.scheduleJob(jobDetail, trigger);
        // pauseJob(quartz.getJobName(),quartz.getJobGroup());
        return new ResponseTemplate(200,"添加成功");

    }
    /**
     * 获取Job状态
     * @param jobName
     * @param jobGroup
     * @return
     * @throws SchedulerException
     */
    public ResponseTemplate getJobState(String jobName, String jobGroup) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(jobName, jobGroup);
        String result =scheduler.getTriggerState(triggerKey).name();
        return new ResponseTemplate(200,"获取成功",result);
    }

    //暂停所有任务
    public ResponseTemplate pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
        return new ResponseTemplate(200,"暂停所有任务成功");

    }

    //暂停任务
    public ResponseTemplate pauseJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return new ResponseTemplate(500,"暂停失败");
        }else {
            scheduler.pauseJob(jobKey);
            return new ResponseTemplate(200,"暂停成功");
        }

    }

    //恢复所有任务
    public ResponseTemplate resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
        return new ResponseTemplate(200,"恢复所有任务成功");

    }

    // 恢复某个任务
    public ResponseTemplate resumeJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return new ResponseTemplate(500,"暂停失败");
        }else {
            scheduler.resumeJob(jobKey);
            return new ResponseTemplate(200,"暂停成功");
        }
    }

    //删除某个任务
    public ResponseTemplate deleteJob(Quartz quartz) throws SchedulerException {
        JobKey jobKey = new JobKey(quartz.getJobName(), quartz.getJobGroup());
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null ) {
            return new ResponseTemplate(500,"jobDetail is null");
        }else if(!scheduler.checkExists(jobKey)) {
            return new ResponseTemplate(500,"jobKey is not exists");
        }else {
            scheduler.deleteJob(jobKey);
            return new ResponseTemplate(200,"删除成功");
        }

    }

    //修改任务
    public ResponseTemplate  modifyJob(Quartz quartz) throws SchedulerException {
        if (!CronExpression.isValidExpression(quartz.getCronExpression())) {
            return new ResponseTemplate(500,"Illegal cron expression");
        }
        TriggerKey triggerKey = TriggerKey.triggerKey(quartz.getJobName(),quartz.getJobGroup());
        JobKey jobKey = new JobKey(quartz.getJobName(),quartz.getJobGroup());
        if (scheduler.checkExists(jobKey) && scheduler.checkExists(triggerKey)) {
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            //表达式调度构建器,不立即执行
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression()).withMisfireHandlingInstructionDoNothing();
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder).build();
            //修改参数
            if(!trigger.getJobDataMap().get("invokeParam").equals(quartz.getInvokeParam())) {
                trigger.getJobDataMap().put("invokeParam",quartz.getInvokeParam());
            }
//            if(quartz.getInvokeParam()!=null && !"".equals(quartz.getInvokeParam())) {
//                trigger.getJobDataMap().put("invokeParam",quartz.getInvokeParam());
//            }
            //按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
            return new ResponseTemplate(200,"修改成功");
        }else {
            return new ResponseTemplate(500,"job or trigger not exists");
        }

    }

}